import cfg from '../config';
import {getView, sid, tab} from '../util/api';
import {formatDate, tabSwitch, getCurrDay, randomColor, isArrContain, isArrNoContain, findStr, backPage, getPrevDate, getNextDate, message, closeMsg, getPinYin, getUserList, getUser} from '../util/aid';
import {setTitle, urlParam, session, getHash, format, jsons, json} from '../lib/kutil';
import * as ajax from '../lib/kajax';
import Dialog from '../lib/kdialog';
const dialog = new Dialog();

//建立ws 连接
import Ws from '../lib/kws';
let _ws = new Ws();

const $ = require('../lib/kdom');
let _view = require('raw!./home.html');

let FromID = null; // 发送PID
let ToID = null; // 接收PID
let TargetID = null; // 回话PID

let IssueID = null; // 回话IssueID
let currentIssue = null; // 当前工单

let listData = null;//列表
let isLoadList = 0; //判断加载列表
let timer = null; //心跳定时器
let perm = null; // 权限

let FromUserData = null;// 登陆用户
let ToUserData = null; // 目标用户

let allUser = null; // 全部用户
let IS_SELF = null; // 是否自己

let CurrSendMsgVal = null; // 当前消息

let msgTitle = null; // 消息的Title 
let msgText = null; // 消息的Text

let isServiceID = true;

let kuaijieData = [
  '您好，为了方便您了解（记忆），我现在将该内容通过短信（彩信）发给您，请您留意查询',
  '不好意思，担误您的时间了',
  '等待之前先提醒：“先生/小姐，请您稍等片刻，我马上为您查询',
  '请您稍等片刻，马上就好',
  '感谢您耐心的等候'
];

let huihuaObj = {
  "9": "企业用户",
  "11": "专家组",
  "14": "线下网点"
};

// 特殊说明
// ^^201707211073,92356991,1^^你好啊
// issue
// pid
// 0发给专职,1发给用户，2发专家，3发给线下

//专家组OPENID
let ZhuanJiaZU = {
  "10": [],
  "11": [],
  "12": [],
  "13": [],
  "14": [],
  "15": [],
  "16": [],
  "17": [],
  "18": [],
  "19": [],
  "20": [],
};
// eyJhbGciOiJIUzI1NiIsICJ0eXAiOiJKV1QifQ.eyJwaWQiOiI4OTM1NDg2NiIsInRhYiI6MSwic2lkIjoiMTEifQ.sX1-zifNGp2YSn5iaNsVsYj4FHaH-Hj8FgcMO4zRWRk

let ZhuanJiaZUData = [];//专家组

let XainXiaZU = [];//线下组
let XainXiaZUData = [];//线下组

export default class {
  path = '/lottery/home$';
  hash = '/lottery/home';
  title = '工银重庆对公客户信息平台';

  constructor(opt) {
    opt = opt || {};
    this.path = opt.path || this.path;
    this.hash = opt.hash || this.hash;
    this.title = opt.title || this.title;
  }

  // 输出视图
  view(cb) {
    if (!_view) {
      // 静态资源浏览器有缓存,增加时标,强制刷新!
      getView(`${cfg.view.home}?t=${(+new Date())}`, '', (rs) => {
        _view = rs;
        cb(null, _view);
      });
    } else
      cb(null, _view);
  }

  // 在已经加载的视图上操作
  bind(dv, params) {
    console.log('我是HOME', params);
    FromID = params.user.pid;
    //
    // FromUserData = params.user; // 用户数据
    // // FromID = FromUserData.pid; // 发送PID 46587413
    // // ToID = "92356991"; // 接收PID
    //
    // perm = 10; //权限
    // // dialog.loading();
    //
    //
    // // 22944740
    // // 22944740
    // // 92356991
    // // 10660954
    //
    // //心跳连接webSocket
    heartConWs();
    timer = setInterval(heartConWs, 30000);


    bindFun();
    loginUserFun(FromUserData);
    loadListFun();
    loadKuaijieFun(kuaijieData);

    // 找出专家 和线下网点
    getUserList('', (rs) => {
      let perm = null;
      let skill = null;
      let oid = null;
      for (let i = 0, o = rs, len = o.length; i < len; i++) {
        perm = o[i].perm[0];
        skill = o[i].skill[0];
        oid = encodeURIComponent(o[i].openid);
        if (perm == '11') {
          // getoOpenIDFun(o[i].mobile, (oid) => {
          //     // console.log(o[i], oid);
          //     if (ZhuanJiaZU[skill])
          //         ZhuanJiaZU[skill].push(encodeURIComponent(oid));
          // });
          console.log(oid);
          if (skill) ZhuanJiaZU[skill].push(oid);
          ZhuanJiaZUData.push(o[i]);
        } else if (perm == '14') {
          // getoOpenIDFun(o[i].mobile, (oid) => {
          //     XainXiaZU.push(encodeURIComponent(oid));
          // });
          XainXiaZU.push(oid);
          XainXiaZUData.push(o[i]);
        } else {
          let isRoster = IS_Roster(params.roster, o[i].mobile);
          if (isRoster) {
            perm = isRoster.perm;
            skill = isRoster.skill;
            if (perm == '11') {
              // getoOpenIDFun(isRoster.mobile, (oid) => {
              //     if (ZhuanJiaZU[skill])
              //         ZhuanJiaZU[skill].push(encodeURIComponent(oid));
              // });
              console.log(oid);
              if (skill) ZhuanJiaZU[skill].push(oid);
              ZhuanJiaZUData.push(o[i]);
            } else if (perm == '14') {
              // getoOpenIDFun(isRoster.mobile, (oid) => {
              //     XainXiaZU.push(encodeURIComponent(oid));
              // });
              XainXiaZU.push(oid);
              XainXiaZUData.push(o[i]);
            }
          }
        }
      }
    });


  }

  /*bind*/
}
// 判断花名册
function IS_Roster(roster, mobile) {
  for (let i = 0, o = roster, len = o.length; i < len; i++) {
    if (o[i]['mobile'] == mobile) return o[i];
  }
  return {};
}

// 选择聊天
function selectChatTagFun(idx) {
  console.log('选择聊天        ', listData[idx]);

  cur = listData[idx]; // 当前工单
  IssueID = listData[idx].id; // 当前工单ID
  TargetID = listData[idx].pid; // 当前工单PID

  // conversationTitleFun(listData[idx]);
}

// 登录用户
function loginUserFun(data) {
  let rc = `<div class="item-cell">
               <img class="head-img" src="${data.headimgurl}" style="margin-top:10px;">
             </div>
             <div class="item-right">
               <span>${data.name}</span>
             </div>`;
  $.html($.id('loginUserBox'), rc)
}

// bind
function bindFun() {

  // 发送消息
  $.id('sendMsgBtn').onclick = () => {
    saveMsgFun(TeShuVal($.id('huihuaTag')));
    sendMsgBtnFun(TeShuVal($.id('huihuaTag')));
    if (isServiceID) {
      isServiceID = false;
      upIssueServiceId();
    }
  };

  // 快捷回复
  $.id('kuaijieTag').onchange = () => {
    $.id('sendMsgVal').value = kuaijieData[$.id('kuaijieTag').value];
  };

  // 转发
  $.id('huihuaTag').onchange = () => {
    let val = $.id('huihuaTag').value;
    // console.log(val);
    conversationTitleFun(val);
    if (val == 11) {
      zhuan_ZJ_Tag();
    } else if (val == 14) {
      zhuan_XX_Tag();
    }
  };

  // 转专家
  $.id('zhuan_ZJ_Tag').onclick = () => {
    conversationTitleFun('11');
    zhuan_ZJ_Tag($.id('zhuan_ZJ_Tag_Val').value);
  };

  // 转线下
  $.id('zhuan_XX_Tag').onclick = () => {
    conversationTitleFun('14');
    zhuan_XX_Tag();
  };

  // tab 切换
  tabSwitch($.qus('#listTabBox .tab-item-cell'), (that) => {
    let val = that.getAttribute('data-val');
    createListFun(listData, val);
  });

}

function upIssueServiceId() {
  ajax.post(`${HOST_URL}${cfg.ogs.upIssueServiceId}`, `id=${IssueID}&serviceId=${FromID}`, (err, rs) => {
    if (rs) {
      console.log(JSON.parse(rs));
    } else {
      isServiceID = true;
    }
  });
}

// 特殊处理
function TeShuVal(tag) {
  let TT = '1'; // 发给谁
  let HHTVal = tag.value; //回话的人
  if (HHTVal == 9) {
    TT = 1;
  } else if (HHTVal == 11) {
    TT = 2;
  } else if (HHTVal == 14) {
    TT = 3;
  }
  return `^^${IssueID},${FromID},${TT}^^`;
}

// 保存
function saveMsgFun() {
  let rs = checkIssueIDFun(IssueID);
  if (rs) {
    let data = {
      issueId: rs.id,
      from: FromID,
      to: ToID,
      msg: JSON.stringify({"M": CurrSendMsgVal, "F": FromID, "T": ToID}),
      pic: [],
      member: JSON.stringify([FromUserData.name, FromUserData.headimgurl]),
      status: 1
    };
    ajax.post(`${HOST_URL}${cfg.ogs.saveMsg}`, data, (err, rs) => {
      console.log(JSON.parse(rs));
    });
  }
}

// 转专家
function zhuan_ZJ_Tag(val) {
  // let huihuaTag = $.id('huihuaTag');
  let param = {
    "oidarr": ZhuanJiaZU[val],
    "issueId": IssueID,
    "pid": FromID,
    "sid": sid(),
    "tab": tab(),
    "title": msgTitle,
    "description": msgText
  };
  console.log('ZhuanJiaZU', ZhuanJiaZU);
  pushMsgFun(param);
}

// 转线下
function zhuan_XX_Tag() {
  let param = {
    "oidarr": XainXiaZU,
    "issueId": IssueID,
    "pid": FromID,
    "sid": sid(),
    "tab": tab(),
    "title": msgTitle,
    "description": msgText
  };
  pushMsgFun(param);
}

// 加载快捷回复内容
function loadKuaijieFun(data) {
  let rc = '<option value="">快捷回复</option>';
  for (let i = 0, o = data, len = o.length; i < len; i++) {
    rc += `<option value="${i}">${data[i]}</option>`;
  }
  $.html($.id('kuaijieTag'), rc);
}

// loadListFun
function loadListFun() {
  ajax.get(`${HOST_URL}${cfg.ogs.issueList}`, "", (rs) => {
    if (rs) {
      let r = JSON.parse(rs);
      listData = r;
      createListFun(r);
    } else {
      // alert('获取工单信息失败！');
    }
  });
}

// 创建列表
function createListFun(data, val) {
  let rc = '';
  let idx = TargetID;
  let status = '';
  let num = null;
  console.log('专职坐席 ', data, val);
  for (let i = 0, o = data, len = o.length; i < len; i++) {
    status = o[i].status;
    // console.log(status);
    if (perm == 10) {
      if (val) {
        if (val == 1) {
          if (status == 1 || status == 0) {
            num += 1;
            rc += createDvsFun(o[i], i, idx, num);
          }
        } else {
          if (status == val) {
            num += 1;
            rc += createDvsFun(o[i], i, idx, num);
          }
        }
      } else {
        if (status == 1 || status == 0) {
          num += 1;
          rc += createDvsFun(o[i], i, idx, num);
        }
      }
    }
  }
  if (rc) {
    $.html($.id('issueListBox'), rc);
    // tab 切换
    tabSwitch($.qus('#issueListBox li'), (that) => {
      let val = that.getAttribute('data-val');
      selectChatTagFun(val);
      loadMsgListFun(listData[val].id);
      $.html($.id('messageListBox'), '');
    });
  } else {
    // $.html($.id('issueListBox'), '');
    // $.html($.id('messageListBox'), '');
    // alert('暂时没有获取到更多的消息!');
  }
  dialog.close();
}

// 设置聊天的title
function conversationTitleFun(data) {
  if (data instanceof Object)
    $.html($.id('conversationTitle'), `${data.title}-${huihuaObj['9']}` || '');
  else
    $.html($.id('conversationTitle'), `${huihuaObj[data]}` || '');
  // huihuaTag.value
}

// 创建片段
function createDvsFun(data, i, idx, num) {
  // console.log('创建片段', data, i, idx, num, ToUserData);
  // let company = data.company[0];

  // let data =

  let rc = '';
  let cls = '';
  if (!data) return rc;
  if (!idx && num == 1) {
    cls = ` active`;

    currentIssue = data; // 当前工单
    IssueID = data.id; // 当前工单ID
    TargetID = data.pid; // 当前工单PID

    conversationTitleFun(data);


    msgTitle = currentIssue.title;
    msgText = currentIssue.text;
    loadMsgListFun(IssueID);
    $.html($.id('messageListBox'), '');
  } else {
    if (idx == data.pid) {
      cls = ` active`;
      loadMsgListFun();
      currentIssue = data; // 当前工单
      IssueID = data.id; // 当前工单ID
      TargetID = data.pid; // 当前工单PID
      console.log('当前工单PID', TargetID);
      loadMsgListFun(IssueID);
      conversationTitleFun(data);
      $.html($.id('messageListBox'), '');
    } else {
      cls = ``;
    }
  }

  console.log(currentIssue);
  console.log('当前工单PID', TargetID);

  rc += `<li class="item-row ${cls}" data-val="${i}">`;
  rc += `<div class="item-cell">
             <img class="avatar" src="img/to-head-img.jpg">
           </div>
           <div class="item-right">
             <p class="gs-title">${data.title}</p>
             <p class="gs-describe">${data.text}</p>
           </div>
         </li >`;
  return rc;
}

// 加载消息内容列表
function loadMsgListFun(id) {
  ajax.get(`${HOST_URL}${cfg.ogs.msgList}`, `issueId=${id}`, (rs) => {
    if (rs) {
      let r = JSON.parse(rs);
      let tempData = null;
      // console.log('加载消息内容列表', r);
      // console.log('回话的ID', TargetID); // 目标
      for (let i = 0, o = r.data, len = o.length; i < len; i++) {
        tempData = {
          name: o[i].member[0],
          headimgurl: o[i].member[1],
        };
        if (TargetID == o[i].from) { // 目标
          IS_SELF = false;
          laodMsgPDdunFun(tempData, o[i].msg)
        } else { // 自己
          IS_SELF = true;
          laodMsgPDdunFun(tempData, o[i].msg)
        }
      }
    } else {
      // alert('获取工单信息失败！');
    }
  });
}

// 加载消息片段
function laodMsgPDdunFun(user, s) {
  // console.log(user, s);
  // console.log('111111111111', user, s);
  // console.log(currentIssue, IssueID, TargetID);

  if (!s.M) return;

  if (s.M.indexOf('^^') > -1) {
    let specialStr = s.M.substring(2, 25).split(',');
    let specialMsg = s.M.substring(28, s.M.length);
    s.M = specialMsg;
    s.id = specialStr[0];
    s.pid = specialStr[1];
    s.target = specialStr[2];
  } else {
  }
  let rc = document.createElement('li');
  let cls = '';
  let _zhuanfa = '';
  if (IS_SELF) {
    cls = 'message-right';
  } else {
    cls = 'message-left';
  }
  // console.log(msg.target)
  if (s.target && s.target != 1 && s.pid != FromID) {
    _zhuanfa = `<div><button class="file-group-button" onclick="Zhuan_Fa_Fun(this)" data='${JSON.stringify(s)}'>转发</button></div>`;
  } else {
    _zhuanfa = '';
  }

  rc.innerHTML = `<div class="message-item ${cls}">
 						<div class="msg-head-portrait">
 							<img class="msg-avatar" src="${user.headimgurl}">
 						</div>
 						<div class="message-text">
 							<div class="name">${user.name}<span>${formatDate('hh:mm')}</span></div>
               <div class="text">${s.M}</div>
             ${_zhuanfa}
             </div>
           </div>`;
  $.id('messageListBox').appendChild(rc);
}
// 接收消息
function receiveMsgFun(s, F) {
  console.log('接收消息1', s, F, ToID);
  s.M = s.M || s['M.G'];

  if (!s.M) return;
  ToID = s.F;
  loadListFun();
  // ^^201707211073,92356991,1^^你好啊
  // issue
  // pid
  // 0发给专职,1发给用户，2发专家，3发给线下

  if (s.M && s.M.indexOf('^^') > -1) {
    let r = s.M.split('^^');
    // let specialStr = s.M.substring(2, 25).split(',');
    // let specialMsg = s.M.substring(28, s.M.length);
    s.M = r['3'];
    let arr = r['2'].split(',');
    s.id = arr[0];
    s.pid = arr[1];
    s.target = arr[2]; // 0发给专职,1发给用户，2发专家，3发给线下
  } else {
  }
  // console.log('接收消息', s, F);

  // 判断是否当前显示工单
  // if (currentIssue.id != IssueID) return;
  // checkIssueIDFun();

  IS_SELF = false;
  if (ToID == s.F) {
    if (ToUserData) {
      laodMsgPDdunFun(ToUserData, s);
    } else {
      getUser('', ToID, (rs) => {
        ToUserData = rs;
        laodMsgPDdunFun(ToUserData, s, F);
      });
    }
  } else {
    ToID = s.F; // 发送过来的ID
    getUser('', ToID, (rs) => {
      ToUserData = rs;
      laodMsgPDdunFun(ToUserData, s);
    });
  }
}

// 发送当前消息
function sendCurrentMsgFun(s, T) {
  console.log('发送当前消息', s, T);
  if (!s) return;
  IS_SELF = true;
  if (s.M != 200) return;
  laodMsgPDdunFun(FromUserData, {"M": sendMsgVal.value}, T);
}

// setScrollHeightFun
function setScrollHeightFun() {
  // let val = $.id('messageListBox').offsetHeight;
  // console.log(val);
  // // $.id('messageBox').scrollTo(0, val);
  // // $.id('messageBox').scrollTop =  $.id('messageBox').scrollHeight;
  // $.id('messageBox').scrollTop = $.id('messageBox').offsetHeight;
}

// 发送消息
function sendMsgBtnFun(val) {
  CurrSendMsgVal = `${val}${sendMsgVal.value}`;

  console.log('发送消息', FromID, ToID, CurrSendMsgVal);
  console.log('发送消息', FromID, TargetID, CurrSendMsgVal);
  _ws.msg(FromID, TargetID, CurrSendMsgVal);
  // _ws.msg(FromID, ToID, CurrSendMsgVal);
}

// 群发
function group(to) {
  _ws.group(FromID, to, CurrSendMsgVal);
}

// // 心跳
function heart() {
  _ws.heart(FromID, `[[1, "个人状态"], [1, "工作状态"]]`);
}

// 心跳定时器
function heartConWs() {
  if (_ws.status == 0) {
    _ws.open();
    heart();
  } else {
    heart();
  }
}
// 打开连接
_ws.onopen = () => {
  // console.log("ws start...");
  setTimeout(heart, 2000);
};

// 接收消息
_ws.onmsg = (s) => {
  console.log('onmsg', s);
  // if (isLoadList < 2)
  //   isLoadList += 1;
  // else if (isLoadList > 2) {
  //   loadListFun();
  // }
  // if (isLoadList > 1) {
  //   if (!s) return;
  //   s = s ? JSON.parse(s) : {};
  //   if (s.M == 200 || s['M.G'] == 200) { //发出去
  //     sendCurrentMsgFun(s, s.F);
  //   } else { //收消息
  //     receiveMsgFun(s, s.T);
  //   }
  //   setScrollHeightFun();
  // }
};

// 检查工单号
function checkIssueIDFun(id) {
  let rc = '';
  for (let i = 0, o = listData, len = o.length; i < len; i++) {
    if (o[i].id == id) return o[i]
  }
  return '';
}

// 获取openID
function getoOpenIDFun(mobile, cb) {
  ajax.post(`${HOST_URL}${cfg.ogs.getOpenId}`, `mobile=${mobile}&sid=${sid()}&tab=${tab()}`, (err, rs) => {
    if (rs) {
      let r = JSON.parse(rs);
      cb(r.openid);
    }
  })
}

// 推送消息
function pushMsgFun(param) {
  console.log('推送消息    param     ', param);
  param = param || {};
  if (param.oidarr.length <= 0) return;

  let link = encodeURIComponent('https://imapi.icbc.com.cn/open/oauth2?scope=base&appid=WaPPsecsKukLNWWKUqXa2Q%3D%3D&redirect=http%3A%2F%2Frel.nuoyadalu.com%2Fogs%2Fmb%2Findex.html?issueId=' + param.issueId + '?pid=' + param.pid + '?sid=' + param.sid + '?tab=' + param.tab + '');
  let sendUrl = encodeURIComponent('http://rel.nuoyadalu.com/rongELianCQOGS/MsgService');
  let msgOther = {
    "title": param.title,
    "description": param.description,
    "url": "",
    "picurl": "PIC_URL",
  };
  msgOther = JSON.stringify(msgOther);
  let data = {
    sendUrl: sendUrl,
    link: link,
    openid: JSON.stringify(param.oidarr),
    msgOther: msgOther,
  };

  ajax.post(`${HOST_URL}${cfg.ogs.pushmsg}`, data, (err, rs) => {
    // console.log(JSON.parse(rs));
  });
}